<template>
  <div class="user">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>会员管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 条件搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入需要查询的内容"
            v-model="searchall"
            clearable
            @clear="clearsearch()"
          >
            <template slot="prepend">按全部查询：</template>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="allSearch()"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="10">
          <el-input
            placeholder="请输入需要查询的用户昵称"
            v-model="searchNick"
            clearable
            @clear="clearsearch()"
          >
            <template slot="prepend">按昵称查询：</template>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="NickSearch()"
            ></el-button>
          </el-input>
        </el-col>
      </el-row>
      <!-- table内容 -->
      <div class="conter">
        <el-table :data="tableData1" border stripe>
          <el-table-column
            type="index"
            :index="indexNum"
            label="序号"
            width="60"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="id" label="用户ID" width="80" align="center">
          </el-table-column>
          <el-table-column
            prop="loginName"
            label="登录账号"
            width=""
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="qq"
            label="用户QQ号"
            width=""
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="用户昵称"
            width=""
            align="center"
          >
          </el-table-column>
          <el-table-column prop="sex" label="用户性别" width="" align="center">
          </el-table-column>
          <el-table-column
            prop="image"
            label="用户头像"
            width=""
            align="center"
          >
            <template slot-scope="scope">
              <img :src="api + scope.row.userIcon" min-width="80" height="80" />
            </template>
          </el-table-column>
          <el-table-column
            prop="createtime"
            label="创建时间"
            width=""
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="updatetime"
            label="修改时间"
            width=""
            align="center"
          >
          </el-table-column>
          <el-table-column label="禁用/启用" width="140" align="center">
            <template slot-scope="scpoe">
              <el-switch
                v-model="scpoe.row.state"
                active-text="启用"
                inactive-text="禁用"
                @change="toggle(scpoe.row.id)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="Edituser(scope.row)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                @click="Deleteuser(scope.row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
         <!-- 分页 -->
        <el-pagination
          @next-click="handleNextClick"
          @prev-click="handlePrevClick"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="5"
          :current-page="currentpage"
          background
          layout="total,sizes, prev, pager, next, jumper"
          :total="tableData_length"
        >
        </el-pagination>
      </div>
      <!-- 添加弹框 对话框-->
      <el-dialog title="编辑" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="用户Id" :label-width="formLabelWidth">
            <el-input
              v-model="form.id"
              autocomplete="off"
              readonly
              title="不可修改"
            ></el-input>
          </el-form-item>
          <el-form-item label="登录账号" :label-width="formLabelWidth">
            <el-input v-model="form.loginName" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户QQ号" :label-width="formLabelWidth">
            <el-input v-model="form.qq" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" :label-width="formLabelWidth">
            <el-input v-model="form.nickname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-input v-model="form.sex" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="头像" :label-width="formLabelWidth">
            <el-upload
              class="avatar-uploader"
              :action="uploadimageapi+'/usericonuploadimage'"
              :show-file-list="false"
              name="usericonfiles"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-button type="primary" @click="Updateuser">提 交</el-button>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [],
      tableData1: [], //分页显示
      searchall: "",
      searchNick: "",
      form: {
        loginName: "",
        qq: "",
        loginPassword: "",
        nickname: "",
        sex: "",
        userIcon: ""
      },
      formLabelWidth: "80px",
      dialogFormVisible: false,
      //图片地址拼接 显示图片
      api: this.imageapi,
      uploadimageapi: this.uploadimageapi,
      imageUrl: "",
      currentpage: 1, //当前页面
      tableData_length: 0, //总条目数
      pageSize: 5,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    //加载用户列表
    init() {
      const that = this;
      that.$http
        .get("/selectuser")
        .then(res => {
          console.log(res);
          if (res.status == 200) {
            that.tableData = res.data;
            that.tableData_length = res.data.length;
            this.handleCurrentChange(1); //默认显示第一页条目
            for (let i in that.tableData) {
              if (that.tableData[i].state == 1) {
                that.tableData[i].state = true;
              } else {
                that.tableData[i].state = false;
              }
            }
          } else {
            that.$message({
              message: "数据请求失败...",
              type: "error"
            });
          }
        })
        .catch(function() {});
    },
    //element table自带序号
    indexNum(index) {
      return (this.currentpage - 1) * this.pageSize + index + 1;
    },
    //switch 开关 禁用或者开启用户
    toggle(id) {
      this.$http.post("/userswitch", { id });
      this.init();
    },
    //获取编辑内容
    Edituser(item) {
      this.dialogFormVisible = true;
      this.imageUrl = this.api + item.userIcon;
      this.form = JSON.parse(JSON.stringify(item));
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.userIcon = res.path;
    },
    Updateuser() {
      const that = this;
      that.$http
        .post("/updateuser", that.form)
        .then(res => {
          if (res.status == 204) {
            that.$message({
              message: "更新数据成功...",
              type: "success"
            });
            that.init();
            that.dialogFormVisible = false;
          } else {
            that.$message({
              message: "更新数据失败...",
              type: "error"
            });
          }
          // console.log(res);
          that.dialogFormVisible = false;
          that.form.loginName = null;
          that.form.loginPassword = null;
          that.form.sex = null;
          that.form.nickname = null;
        })
        .catch(function() {});
    },
    Deleteuser(id) {
      const that = this;
      that
        .$confirm("此操作将数据永久删除,不可恢复, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true
        })
        .then(() => {
          that.$http.post("/deleteuser", { id }),
            that.$message({
              type: "success",
              message: "删除成功!"
            });
         for (let i in that.tableData1) {
            if (that.tableData1[i].id == id) {
              that.tableData1.splice(i, 1); //删除不请求数据，直接在数组中删除
              break;
            }
          }
        })
        .catch(() => {
          that.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //处理数据,分页
    handleTableData() {
      this.tableData1 = this.tableData.slice(
        (this.currentpage - 1) * this.pageSize,
        this.currentpage * this.pageSize
      );
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.pageSize = val;
      this.handleTableData();
    },
    //点击中间页的按钮 执行的方法
    handleCurrentChange(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //点击向前的按钮 执行的方法
    handlePrevClick(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //点击向后的按钮 执行的方法
    handleNextClick(val) {
      this.oldPage = val;
      this.currentpage = val;
      this.handleTableData();
    },
    //清除搜索框
    clearsearch() {
      this.init();
    },
    //按用户昵称查询
    NickSearch(){
       if (this.searchNick == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else {
        let search = this.searchNick;
        this.tableData = this.tableData.filter(item => {
          let searchField = { nickname: item.nickname };
          return Object.keys(searchField).some(key => {
            return (
              String(item[key])
                .toLowerCase()
                .indexOf(search) > -1
            );
          });
        });
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    },
    //安装全部查询过滤
    allSearch(){
      if (this.searchall == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      } else if (this.searchall) {
        this.tableData = this.tableData.filter(item => {
          let res = JSON.stringify(item);
          if (res.indexOf(this.searchall) != -1) {
            return true;
          } else {
            return false;
          }
        });
      } else {
        this.tableData1 = this.tableData;
      }
      this.tableData_length = this.tableData.length;
      this.handleCurrentChange(1);
    },
  }
};
</script>

<style scoped>
.el-input {
  margin-bottom: 8px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>